# -*- coding: utf-8 -*-
import logging

from django.core.exceptions import ValidationError
from django.core.handlers.wsgi import WSGIRequest
from django.http.response import JsonResponse, HttpResponse
from django.utils.deprecation import MiddlewareMixin

from firstDjango.exceptions import FormException


logger = logging.getLogger()


class LoginMiddleware(MiddlewareMixin):
    ignore_paths = {
        "/api/user/login",
        "/api/user/register",
        "/api/book/fetch_books",
        "/api/comment/fetchByBookId"
    }

    def process_request(self, request: WSGIRequest):
        path = request.path
        if path in self.ignore_paths:
            return None
        if request.session.get('user'):
            return None
        return JsonResponse({"code": -100, "message": '用户未登录'})


class ExceptionMiddleware(MiddlewareMixin):
    def process_exception(self, request, exception):
        if isinstance(exception, FormException):
            logger.exception("请求异常: raw_err:%s", exception.raw_exception)
            return JsonResponse({"code": -200, "message": exception.message})
        if isinstance(exception, ValidationError):
            return JsonResponse({"code": -200, "message": exception.message})
        logger.exception("请求异常: err:%s", exception)
        return JsonResponse({"code": -300, "message": "系统错误"})


class ResponseMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if response is None:
            return JsonResponse({"code": 0, "message": "ok"})
        if isinstance(response, HttpResponse):
            return response
        return JsonResponse({"code": 0, "message": "ok", "data": response})

